﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Collections.Concurrent;
using System.Threading;

namespace EliteServer
{
    public class Server
    {
        private TcpListener _server;
        private bool serverHasToBeClose;

        private ConcurrentBag<TcpClient> _clients = new ConcurrentBag<TcpClient>();

        public void StartServer()
        {
            // Set the TcpListener on port 13000.
            Int32 port = 13000;
            IPAddress ipadress = null;
            //IPHostEntry host = Dns.GetHostEntry("minecanardo.no-ip.org");
            //IPAddress ipAddress = host.AddressList[0];

            var adressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            for (int i = 0; i < adressList.Count(); i++)
            {
                if (adressList[i].ToString().Length > 8)
                {
                    ipadress = adressList[i];
                    break;
                }
            }

            ///IPAddress ipAddress = IPAddress.Parse("192.168.1.28");

            _server = new TcpListener(ipadress, port);

            // Start listening for client requests.
            _server.Start();
        }

        public void Loop()
        {
            while (!serverHasToBeClose)
            {
                TcpClient client = _server.AcceptTcpClient();

                // Sauvegarde du client dans la liste, si il n'est pas connu
                if (!_clients.Contains(client))
                    _clients.Add(client);

                // Ecoute des messages envoyés par les différents processus
                NetworkStream stream = client.GetStream();
                var data = new Byte[256];
                Int32 bytes = stream.Read(data, 0, data.Length);
                var responseData = System.Text.Encoding.Default.GetString(data, 0, bytes);
            }

            _server.Stop();
        }
        
        public void Close()
        {
            SendMessage("/exit");
            serverHasToBeClose = true;
        }

        public void SendMessage(string message)
        {
            foreach (var client in _clients)
            {
                NetworkStream stream = client.GetStream();

                Byte[] data = System.Text.Encoding.Default.GetBytes(message);
                stream.Write(data, 0, data.Length);
            }    
        }

        public void SendToEliteInfos(string serializedData)
        {
            NetworkStream stream = _clients.First().GetStream();
            Byte[] data = System.Text.Encoding.Default.GetBytes(serializedData);
            stream.Write(data, 0, data.Length);
        }
    }
}
